#include "mainwindow.h"
#include "ui_mainwindow.h"
//#include "spinboxdelegate.h"
#include "dialogconfirmsale.h"
#include "dialogsettings.h"

#include <QTimer>
#include <QFile>
#include <QSettings>
#include <QHostInfo>
#include <QNetworkInterface>
#include <QMessageBox>
#include <QCloseEvent>
#include <QDebug>
#include <QStandardItemModel>
#include <QDateTime>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QCoreApplication::setOrganizationName("Ingos Helfer");
    QCoreApplication::setApplicationName("FlohmarktPOS");


    ui->setupUi(this);

    restoreSettings ();
    QTimer::singleShot(0,this,SLOT(setup()));

    m_sellerModel=new QStandardItemModel(this);
    ui->tableViewSellers->setModel (m_sellerModel);


    m_salesModel=new QStandardItemModel(this);
    //connect(m_salesModel,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(slotItemChanged(QStandardItem*)));
    ui->tableViewSales->setModel (m_salesModel);
    ui->tableViewSales->setSellerModel(m_sellerModel);
    connect(ui->tableViewSales,SIGNAL(totalSumChanged(double)),ui->lineEditTotal,SLOT(setValue (double)));
    connect(ui->tableViewSales,SIGNAL(salesCleared()),this,SLOT(slotSalesCleared()));

    ui->tableViewSales->clearSalesRows ();
}

MainWindow::~MainWindow()
{
    saveSettings ();
    delete ui;
}

void MainWindow::setup()
{
    readSellersList();
    readSalesPoint();
    updateViews ();
}

void MainWindow::readSellersList()
{
    QFile file("Verkaufsnummernliste.csv");
    if (!file.open (QFile::ReadOnly))
    {
        QMessageBox::critical (this,
                               trUtf8 ("Problem"),
                               trUtf8 ("Die Verkäuferliste konnte nicht geladen werden!"
                                       "\nBitte überprüfen, dass die Datei \"Verkaufsnummernliste.csv\" vorhanden ist"));
        return;
    }

    QString data=file.readAll ();
    file.close ();

    m_sellerModel->clear ();
    m_sellerModel->setColumnCount (2);
    m_sellerModel->setHorizontalHeaderLabels (QStringList() << trUtf8 ("Nummer") << trUtf8 ("Name"));

    QStringList rows=data.split ("\n");
    foreach (QString rowData,rows)
    {
        //qDebug() << "Reading row " << rowData;
        QStringList columns=rowData.split (";");
        for (int i=0;i<columns.count ();i++)
        {
            // check for ; enclosed in quotes
            if (columns.at(i).startsWith("\""))
            {
                columns[i]+=";"+columns.at (i+1);
                columns.removeAt (i+1);
            }
            columns[i].remove ("\"");
        }
        if (columns.count ()>3)
        {
            bool ok;
            // 1st column is a number ==> a valid seller row
            if (columns.at(0).toInt (&ok) && !columns.at(1).isEmpty ())
            {
                int row=m_sellerModel->rowCount ();

                m_sellerModel->insertRow(row);
                m_sellerModel->setData(m_sellerModel->index(row,0),columns.at(0));
                m_sellerModel->setData(m_sellerModel->index(row,1),columns.at(1));
            }
        }

    }
    ui->tableViewSellers->resizeColumnsToContents ();
}

void MainWindow::readSalesPoint()
{
    QSettings settings;

    QString text;
    text=QHostInfo::localHostName()+"_"+QNetworkInterface::allInterfaces().at(0).hardwareAddress().replace (':','_');
    m_salesPointName=settings.value("salesPoint",text).toString();
    if (m_salesPointName.isEmpty ())
    {
        m_salesPointName=text;
        QSettings settings;
        settings.setValue("salesPoint",m_salesPointName);
    }

    ui->leSalesPoint->setText(m_salesPointName);
}

void MainWindow::slotSalesCleared()
{

    ui->cbNewSale->setEnabled (true);
    ui->cbCancelSale->setEnabled (false);
    ui->cbCompleteSale->setEnabled (false);
    ui->tableViewSales->setEnabled (false);
    ui->toolButtonRemoveLine->setEnabled (false);
    ui->lineEditTotal->setValue (0);
    ui->cbNewSale->setFocus ();
}




void MainWindow::updateHistory()
{
    QString text;
    QString time=QTime::currentTime ().toString (Qt::TextDate);
    text=trUtf8 ("%1 : %2")
            .arg(time)
            .arg(ui->lineEditTotal->text ());

    text=text+"\n"+ui->textEdit->toPlainText ();
    ui->textEdit->setPlainText (text);
}

bool MainWindow::saveSaleToFile()
{
    QString fileName=m_salesPointName+".pos";
    QFile file(fileName);
    if (!QFile::exists (fileName))
    {
        if (!file.open (QFile::ReadWrite))
        {
            QMessageBox::critical (this,
                                   trUtf8 ("Problem beim Speichern"),
                                   trUtf8 ("Der Verkauf konnte nicht abgespeichert werden!\nFehler: %1").arg(file.errorString ()));
            return false;
        }
        else
        {
            QString header;
            header=trUtf8 ("POS;Transaktion;Verkäufer;Anzahl;Einzelpreis;Summe\n");
            file.write(header.toUtf8 ());
        }
    }
    else
    {
        if (!file.open (QFile::Append))
        {
            QMessageBox::critical (this,
                                   trUtf8 ("Problem beim Speichern"),
                                   trUtf8 ("Der Verkauf konnte nicht abgespeichert werden!\nFehler: %1").arg(file.errorString ()));
            return false;
        }
    }
    QString timeStamp=QDateTime::currentDateTimeUtc ().toString (Qt::ISODate);
    for (int row=0;row<m_salesModel->rowCount ();row++)
    {
        QString data=m_salesModel->item (row,3)->text ();
        data.remove(trUtf8 ("€"));
        double sum=data.toDouble ();
        if (sum!=0)
        {
            QString line=QString("%1;%2;%3;%4;%5;%6\n")
                    .arg (m_salesPointName)
                    .arg(timeStamp)
                    .arg(m_salesModel->item (row,0)->text ())
                    .arg(m_salesModel->item (row,1)->text ())
                    .arg(m_salesModel->item (row,2)->text ().remove(trUtf8 ("€")))
                    .arg(m_salesModel->item (row,3)->text ().remove(trUtf8 ("€")));
            file.write (line.toUtf8 ());

        }
    }
    // update history view
    updateHistory();

    file.close ();
    return true;
}

void MainWindow::on_leSalesPoint_editingFinished()
{
    if (ui->leSalesPoint->text()!=m_salesPointName)
    {
        if (QMessageBox::question(this,
                                  trUtf8 ("Name der Verkaufsstelle"),
                                  trUtf8 ("Der Name der Verkaufsstelle wurde von %1 nach %2 geändert. Soll diese Änderung übernommen werden?")
                                  .arg(m_salesPointName)
                                  .arg(ui->leSalesPoint->text()),
                                  QMessageBox::Yes|QMessageBox::No,
                                  QMessageBox::No)==QMessageBox::Yes)
        {
            m_salesPointName=ui->leSalesPoint->text();
            QSettings settings;
            settings.setValue("salesPoint",m_salesPointName);
        }
        else
        {
            ui->leSalesPoint->setText(m_salesPointName);
        }
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (!ui->cbNewSale->isEnabled ())
    {
        if (QMessageBox::warning (this,
                                  trUtf8 ("Programm schliessen"),
                                  trUtf8 ("Ein Verkauf wurde noch nicht abgeschlossen! Soll das Programm trotzdem beendet werden?"
                                          "\nDer aktuelle Verkauf wird nicht gesichert!"),
                                  QMessageBox::Yes|QMessageBox::No)==QMessageBox::No)
        {
            event->ignore();
        }
        else
        {
            event->accept ();
        }
    }
    else
    {
        event->accept ();
    }
}

void MainWindow::on_actionSchliessen_triggered()
{
    close ();
}

void MainWindow::startNewSale()
{
    ui->tableViewSales->addEmptySalesRow();

    ui->cbNewSale->setEnabled (false);
    ui->cbCancelSale->setEnabled (true);
    ui->cbCompleteSale->setEnabled (true);
    ui->tableViewSales->setEnabled (true);
    ui->toolButtonRemoveLine->setEnabled (true);
    ui->tableViewSales->setFocus ();
}

void MainWindow::on_cbNewSale_clicked()
{
    startNewSale();
}

void MainWindow::on_cbCancelSale_clicked()
{
    if (QMessageBox::question (this,
                               trUtf8 ("Abbruch eines Verkausvorgangs"),
                               trUtf8 ("Soll der aktuelle Verkauf abgebrochen werden?\n"
                                       "Alle eingegebenen Daten gehen verloren!"),
                               QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes)
    {
        ui->tableViewSales->clearSalesRows();

    }
}

/*
void MainWindow::slotItemChanged(QStandardItem *item)
{
    int row=item->row ();
    QString data=item->data (Qt::DisplayRole).toString().remove(trUtf8 ("€")).trimmed();

    if ((row==m_salesModel->rowCount ()-1) && (item!=0) && (data.toDouble ()>0))
    {
        addEmptySalesRow ();
    }

    switch (item->column ())
    {
    // seller has changed, check if it exists
    case 0:
    {
        QString seller=item->text ();
        QBrush brush;
        QList<QStandardItem *> list=m_sellerModel->findItems (seller,Qt::MatchExactly,0);
        if (list.count ()==0)
        {
            brush.setColor (Qt::red);
            m_salesModel->item (row,4)->setText ("");
        }
        else
        {
            brush.setColor (Qt::white);
            QString name=m_sellerModel->item (list.at(0)->row (),1)->text ();
            m_salesModel->item (row,4)->setText (name);
            ui->tableViewSales->resizeColumnToContents (4);
        }
        item->setBackground (brush);
        item->setData (brush,Qt::BackgroundRole);
        break;
    }
        // quantity or amount has changed
    case 1:
    case 2:
    {
        if (m_salesModel->item (row,1)!=0 && m_salesModel->item (row,2)!=0)
        {
            QString qty=m_salesModel->item (row,1)->text ();
            QString amount=m_salesModel->item (row,2)->text ();
            amount.chop(1);
            double sum= qty.toDouble()*amount.toDouble();
            m_salesModel->item (row,3)->setText (trUtf8 ("%1 €").arg(sum,0,'f',2));
            calculateTotalSum();
        }
        break;
    }
    }
}
*/

void MainWindow::restoreSettings()
{
    QSettings settings;
    restoreState ( settings.value ( "windowState", "0" ).toByteArray() );
    restoreGeometry( settings.value ( "windowGeometry", "0" ).toByteArray() );
    m_showQty=settings.value("showQuantity",true).toBool ();
}
void MainWindow::saveSettings()
{
    QSettings settings;
    settings.setValue ( "windowState", saveState(0));
    settings.setValue ( "windowGeometry", saveGeometry());
    settings.setValue ( "showQuantity",m_showQty);
}

/*
void MainWindow::calculateTotalSum()
{
    double total=0;
    for (int row=0;row<m_salesModel->rowCount ();row++)
    {
        QString data=m_salesModel->item (row,3)->text ();
        data.remove(trUtf8 ("€"));
        total += data.toDouble ();
    }
    ui->lineEditTotal->setValue (total);
}
*/

void MainWindow::on_toolButtonRemoveLine_clicked()
{
    ui->tableViewSales->removeCurrentRow();
}

void MainWindow::on_cbCompleteSale_clicked()
{
    DialogConfirmSale dialog;
    dialog.setAmountDue (ui->lineEditTotal->value());
    if (dialog.exec ()==DialogConfirmSale::Accepted)
    {
        if (saveSaleToFile())
        {
            ui->tableViewSales->clearSalesRows ();
            startNewSale ();
        }
    }
}

void MainWindow::on_actionEinstellungen_triggered()
{
    DialogSettings dialog;
    dialog.setShowQty (m_showQty);
    if (dialog.exec ()==QDialog::Accepted)
    {
        m_showQty=dialog.showQty ();
        updateViews();
    }
}

void MainWindow::updateViews()
{
    if (m_showQty)
    {
        ui->tableViewSales->showColumn (1);
        ui->tableViewSales->showColumn (3);
    }
    else
    {
        ui->tableViewSales->hideColumn (1);
        ui->tableViewSales->hideColumn (3);
    }
}
